package com.tencent.qf.team.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.qf.mybatis.pojo.PageRequest;
import com.tencent.qf.mybatis.pojo.PageResult;
import com.tencent.qf.team.dal.DmAppSalesOrganizationalPerformance;
import com.tencent.qf.team.dal.DmAppSalesPersonalPerformance;
import com.tencent.qf.team.dal.DmAppSalesTutorPerformance;
import com.tencent.qf.team.dal.DmAppSalesTutorPerformanceExample;
import com.tencent.qf.team.dao.DmAppSalesPersonalPerformanceDao;
import com.tencent.qf.team.dao.DmAppSalesTutorPerformanceDao;
import com.tencent.qf.team.dto.request.PersonalPerformanceRequest;
import com.tencent.qf.team.dto.request.SalesPersonalPerformancePrimaryList;
import com.tencent.qf.team.dto.request.TutorPerformanceByGroupIdRequest;
import com.tencent.qf.team.dto.request.TutorPerformanceRequest;
import com.tencent.qf.team.dto.response.GuiderSharePaginateResponse;
import com.tencent.qf.team.dto.response.PerformanceSummaryPersonalListResponse;
import com.tencent.qf.team.service.SalesPerformanceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SalesPerformanceServiceImpl implements SalesPerformanceService {

    @Autowired
    private DmAppSalesTutorPerformanceDao dmAppSalesTutorPerformanceDao;
    @Autowired
    private DmAppSalesPersonalPerformanceDao dmAppSalesPersonalPerformanceDao;

    /**
     * 导师业绩
     *
     * @param request
     * @return
     */
    @Override
    public DmAppSalesTutorPerformance tutorPerformance(TutorPerformanceRequest request) {
        DmAppSalesTutorPerformanceExample example = new DmAppSalesTutorPerformanceExample();
        example.createCriteria().andSalesDateEqualTo(request.getSalesDate())
                .andTutorUidEqualTo(request.getTutorUid())
                .andRootNodeGroupIdEqualTo(request.getRootNodeRroupId());
        List<DmAppSalesTutorPerformance> dmAppSalesTutorPerformances = dmAppSalesTutorPerformanceDao.selectByExample(example);
        if (CollectionUtils.isEmpty(dmAppSalesTutorPerformances)) {
            // 返回0值
            return new DmAppSalesTutorPerformance();
        }
        return dmAppSalesTutorPerformances.get(0);
    }

    /**
     * 个人业绩
     *
     * @param request
     * @return
     */
    @Override
    public List<DmAppSalesPersonalPerformance> personalPerformance(List<PersonalPerformanceRequest> request) {
        SalesPersonalPerformancePrimaryList performancePrimaryList = this.buildParam(request);
        List<DmAppSalesPersonalPerformance> dmAppSalesPersonalPerformances = dmAppSalesPersonalPerformanceDao.selectByPrimaryList(performancePrimaryList);
        if (CollectionUtils.isEmpty(dmAppSalesPersonalPerformances)) {
            return Collections.emptyList();
        }
        dmAppSalesPersonalPerformances.stream().forEach(e -> {
            e.setSalesAmt(this.roundDown(e.getSalesAmt()));
            e.setSalesAtv(this.roundDown(e.getSalesAtv()));
            e.setSalesIncomeAmt(this.roundDown(e.getSalesIncomeAmt()));
            e.setSalesSelfIncomeAmt(this.roundDown(e.getSalesSelfIncomeAmt()));
            e.setSalesPromoteIncomeAmt(this.roundDown(e.getSalesPromoteIncomeAmt()));
        });
        return dmAppSalesPersonalPerformances;
    }

    /**
     * 查组织下所有导师业绩
     *
     * @param request
     * @return
     */
    @Override
    public List<DmAppSalesTutorPerformance> tutorPerformanceByGroupId(TutorPerformanceByGroupIdRequest request) {
        List<DmAppSalesTutorPerformance> data = dmAppSalesTutorPerformanceDao.selectByGroupId(request);
        if (CollectionUtils.isEmpty(data)) {
            return Collections.emptyList();
        }
        if (StringUtils.isNotEmpty(request.getSalesDateBegin()) && StringUtils.isNotEmpty(request.getSalesDateEnd())) {
            // groupId维度分组求和
            Map<String, DmAppSalesTutorPerformance> resultMap = new HashMap<>();
            for (DmAppSalesTutorPerformance performance : data) {
                String key = performance.getTutorUid() + performance.getRootNodeGroupId()
                        + performance.getFirstGroupId() + performance.getSecondGroupId() + performance.getThirdGroupId();
                if (resultMap.containsKey(key)) {
                    DmAppSalesTutorPerformance value = resultMap.get(key);
                    value.setSalesAmt(value.getSalesAmt().add(performance.getSalesAmt()));
                    value.setSalesIncomeAmt(value.getSalesIncomeAmt().add(performance.getSalesIncomeAmt()));
                    value.setSalesOrderNum(value.getSalesOrderNum() + performance.getSalesOrderNum());
                    value.setSalesUserNum(value.getSalesUserNum() + performance.getSalesUserNum());
                    value.setSalesSelfIncomeAmt(value.getSalesSelfIncomeAmt().add(performance.getSalesSelfIncomeAmt()));
                    value.setSalesPromoteIncomeAmt(value.getSalesPromoteIncomeAmt().add(performance.getSalesPromoteIncomeAmt()));
                    value.setSalesPlatformBalanceAmt(value.getSalesPlatformBalanceAmt().add(performance.getSalesPlatformBalanceAmt()));
                    value.setUpdateTime(performance.getUpdateTime());
                    if (performance.getUpdateTime().after(value.getUpdateTime())) {
                        value.setUpdateTime(performance.getUpdateTime());
                    }
                    value.setSalesIncomeAmtAll(value.getSalesIncomeAmtAll().add(performance.getSalesIncomeAmt()));
                    value.setOverchargeSalesIncomeAmt(value.getOverchargeSalesIncomeAmt().add(performance.getOverchargeSalesIncomeAmt()));
                    value.setPromoteIncomeAmtAll(value.getPromoteIncomeAmtAll().add(performance.getPromoteIncomeAmtAll()));
                    value.setSelfIncomeAmtAll(value.getSelfIncomeAmtAll().add(performance.getSelfIncomeAmtAll()));
                    value.setBaseIncomeAmt(value.getBaseIncomeAmt().add(performance.getBaseIncomeAmt()));
                } else {
                    resultMap.put(key, performance);
                }
            }
            data = new ArrayList<>(resultMap.values());
            // 计算客单价
            this.calculationSalesAtv(data);
        }
        return data;
    }

    /**
     * 组织业绩-查组织下所有导师业绩-分页
     *
     * @param request
     * @return
     */
    @Override
    public PageResult<DmAppSalesTutorPerformance> tutorPerformanceByGroupIdPaginate(PageRequest<TutorPerformanceByGroupIdRequest> request) {
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<DmAppSalesTutorPerformance> data = dmAppSalesTutorPerformanceDao.selectByGroupIdPaginate(request.getData());
        PageInfo<DmAppSalesTutorPerformance> pageInfo = new PageInfo(data);
        // 计算客单价
        this.calculationSalesAtv(data);
        return PageResult.build(pageInfo);
    }

    /**
     * 计算客单价
     * @param data
     */
    private void calculationSalesAtv(List<DmAppSalesTutorPerformance> data) {
        // 计算客单价
        for (DmAppSalesTutorPerformance item : data) {
            //订单金额
            BigDecimal salesAmt = item.getSalesAmt();
            //订单数量
            Integer salesOrderNum = item.getSalesOrderNum();
            if (salesOrderNum == 0) {
                item.setSalesAtv(BigDecimal.ZERO);
                continue;
            }
            //客单价
            BigDecimal divide = salesAmt.divide(new BigDecimal(salesOrderNum), 2, RoundingMode.DOWN);
            item.setSalesAtv(divide);
        }
    }


    private BigDecimal roundDown(BigDecimal data) {
        if (data == null) {
            return null;
        }
        return data.setScale(0, BigDecimal.ROUND_DOWN);
    }

    private SalesPersonalPerformancePrimaryList buildParam(List<PersonalPerformanceRequest> request) {
        SalesPersonalPerformancePrimaryList performancePrimaryList = new SalesPersonalPerformancePrimaryList();
        Set<String> guideUids = new HashSet<>();
        Set<String> uids = new HashSet<>();
        Set<String> groupIdPaths = new HashSet<>();
        Set<String> salesDates = new HashSet<>();
        request.stream().forEach(e -> {
            if (StringUtils.isNotEmpty(e.getSalesDate())) {
                salesDates.add(e.getSalesDate());
            }
            if (StringUtils.isNotEmpty(e.getGuideUid())) {
                guideUids.add(e.getGuideUid());
            }
            if (StringUtils.isNotEmpty(e.getUid())) {
                uids.add(e.getUid());
            }
            if (StringUtils.isNotEmpty(e.getGroupIdPath())) {
                groupIdPaths.add(e.getGroupIdPath());
            }
        });
        if(!CollectionUtils.isEmpty(salesDates) && salesDates.size() == 1){
            performancePrimaryList.setSalesDate(salesDates.stream().findFirst().get());
        }
        if(!CollectionUtils.isEmpty(salesDates) && salesDates.size() > 1){
            performancePrimaryList.setSalesDates(salesDates);
        }
        performancePrimaryList.setGuideUids(guideUids);
        performancePrimaryList.setUids(uids);
        performancePrimaryList.setGroupIdPaths(groupIdPaths);
        return performancePrimaryList;
    }
}
